package cn.yoyo.dao;

import cn.yoyo.entity.BlogType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class BlogTypeDaoImpl implements BlogTypeDao{
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public List<BlogType> findAll() {
        return mongoTemplate.findAll(BlogType.class);
    }

    @Override
    public BlogType findById(String typeId) {
        Query query = new Query(Criteria.where("id").is(typeId));
        return mongoTemplate.findOne(query,BlogType.class);
    }

    @Override
    public void add(BlogType blogType) {
        mongoTemplate.insert(blogType);
    }

    @Override
    public void updateSum(String typeId, Integer sum) {
        Update update = new Update();
        Query query = new Query(Criteria.where("id").is(typeId));
        update.set("sum",sum);
        mongoTemplate.updateFirst(query,update,BlogType.class);
    }

    @Override
    public void update(BlogType blogType) {
        Update update = new Update();
        Query query = new Query(Criteria.where("id").is(blogType.getId()));
        if (blogType.getName()!=null){
            update.set("name",blogType.getName());
        }
        mongoTemplate.updateFirst(query,update,BlogType.class);
    }

    @Override
    public void deleteById(String typeId) {
        Query query = new Query(Criteria.where("id").is(typeId));
        mongoTemplate.findAndRemove(query,BlogType.class);
    }
}
